import { objectAny } from "uni-simple-router";

// console.log(urlEncode(arr||obj).slice(1))//调用
var Arr = {
	// 获取元素或对象在数组中的索引位置
	getIndex(arr : any, obj : any) : number {
		let index = -1;
		let key = Object.keys(obj)[0];
		arr.every(function (value : any, i : any) {
			if (value[key] === obj[key]) {
				index = i;
				return false;
			}
			return true;
		});
		return index;
	},
	// 从数组中删除元素或对象
	del(oldArr : any, obj : any) {
		// Array.prototype.baoremove= function(dx) { 
		// 	  if(isNaN(dx)||dx>this.length){return false;} 
		// 	  this.splice(dx,1); 
		// }
		var idx : number = Arr.getIndex(oldArr, obj);
		if (idx >= 0) {
			oldArr.slice(idx, 1);
		} else {

		}
		return oldArr;
	}
}
var Obj = {
	update(oldobj : any, newobj : any) {
		for (var o in oldobj) {
			if (newobj[o]) {
				oldobj[o] = newobj[o];
			}
		}
		return oldobj;
	}
}
function isArrayFn(value : any) {
	if (typeof Array.isArray === "function") {
		return Array.isArray(value);
	} else {
		return Object.prototype.toString.call(value) === "[object Array]";
	}
}
/**
 * 将数据格式化成树形结构返回数组 注意id===数组索引
 * 要点 如果存在父pid 就把自己id作为父组的主键
 * @author yichen
 * @param object 
 * @return Arr
 */
function getTree(Objdata : any) {
	var obj = Objdata || {};
	var data : any = [];
	for (let i in obj) {
		if (obj[i].pid) {
			obj[obj[i].pid] = obj[obj[i].pid] || {};
			obj[obj[i].pid]['children'] = obj[obj[i].pid]['children'] || [];
			obj[obj[i].pid]['children'].push(obj[i]);
		} else {
			data.push(obj[i]);
		}
	}
	return data;
}
export function arrToTree(data : Array<any>, key = "id", parentKey = "pid", childrenKey = "children") {
	let result : Array<any> = []
	if (!Array.isArray(data)) {
		return result
	}
	data.forEach(item => {
		delete item[childrenKey];
	});
	let map : objectAny;
	data.forEach(item => {
		map[item[key]] = item;
	});
	data.forEach(item => {
		let parent : any
		parent = map[item[parentKey]];
		if (parent) {
			(parent[childrenKey] || (parent[childrenKey] = [])).push(item);
		} else {
			result.push(item);
		}
	});
	return result;
}
var objUpdate = Obj.update;
var arrDel = Arr.del;
var arrGetIndex = Arr.getIndex;
//   var isArrayFn=isArrayFn;
//   var getTree=getTree;
export default {
	objUpdate,
	arrDel,
	arrGetIndex,
	isArrayFn,
	getTree,
	arrToTree
}